<?php

class DatabaseObject_ShopReviews extends DatabaseObject {

    public $_shop = null;
    public $user = null;
    public $shop = null;
    public $_author = null;

    public function __construct($db) {
        parent::__construct($db, 'shop_reviews', 'id');

        $this->add('user_id');
        $this->add('shop_id');
        $this->add('text');
        $this->add('date');
        $this->add('type'); // positive = 1, negative = 2, neutral = 0
    }

    public function postLoad() {
        parent::postLoad();

        $this->_shop = new DatabaseObject_Shop($this->getDb());
        $this->_shop->load($this->shop_id);

        $this->_author = new DatabaseObject_User($this->getDb());
        $this->_author->load($this->user_id);

        return true;
    }

    public static function GetReviews($db, $options = array(), $type) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'u.id'
        );

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'u.*');
        
        if (isset($type) && $type != '') {
            $select->where('type = ?', $type);
        }
        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);
        if (isset($options['where']) && $options['where']!='')
            $select->where($options['where']);

        $select->order($options['order']);

        // получим данные из базы
        $select->__toString();
        $data = $db->fetchAll($select);

        // сделаем из полученных записей объекты класса
        $cats = self::BuildMultiple($db, __CLASS__, $data);
        $cat_ids = array_keys($cats);

        foreach ($cats as $key => $value) {
            $user = new DatabaseObject_User($db);
            $shop = new DatabaseObject_User($db);

            $user->load($value->user_id);
            $shop->load($value->shop_id);

            $value->user = $user;
            $value->shop = $shop;
        }
        if (count($cat_ids) == 0)
            return array();

        return $cats;
    }

    public static function GetCount($db, $type) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        if ($type != '') {
            $select->where('type = ?', $type);
        }
        return $db->fetchOne($select);
    }

    public static function CanPost($db, $userId, $shopId) {
        return DatabaseObject_Basket::canWriteComment($db, $userId, $shopId) > 0;
    }

    private static function _GetBaseQuery($db, $options) {
        // инициализируем параметры
        $defaults = array('id' => array());

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создадим запрос
        $select = $db->select();
        $select->from(array('u' => 'shop_reviews'), array());

        // отфильтруем записи по id (если задано)
      
        if (count($options['id']) > 0 ) {
            $select->where('u.id in (?)', $options['id']);
        }

        return $select;
    }

    public static function GetShopReviews($db, $shopId, $limit, $offset, $type = '') {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'u.*');
        $select->where('shop_id = ?', $shopId);
        if ($type != '') {
            $select->where('type = ?', $type);
        }
        $select->order('date desc');
        $select->limit(sprintf('%d,%d', $offset, $limit));

        $data = $db->fetchAll($select);

        $reviews = self::BuildMultiple($db, __CLASS__, $data);

        foreach ($reviews as $rev) {
            $rev->_author = new DatabaseObject_User($db);
            $rev->load($rev->user_id);
        }

        return $reviews;
    }

    public static function GetShopReviewsCount($db, $shopId, $type = '') {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        $select->where('shop_id = ?', $shopId);

        if ($type != '') {
            $select->where('type = ?', $type);
        }
        return $db->fetchOne($select);
    }

    public static function GetShopRatio($db, $shopId) {
        $posCount = self::GetShopReviewsCount($db, $shopId, '1');
        $allCount = self::GetShopReviewsCount($db, $shopId);

        return (float) ((float) $posCount / (float) $allCount);
    }

}
